package com.leetcodehot.problems;

public class problems98 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 一、从上到下传入范围
     */
    /*
    private boolean dfs(TreeNode root, long min, long max) {
        if (root == null) return true;
        int x = root.val;
        if (x <= min || x >= max) {
            return false;
        }
        return dfs(root.left,min,x) && dfs(root.right,x,max);
    }

    public boolean isValidBST(TreeNode root) {
        return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
    */

    /**
     * 二、从底部到上，先左 后右 再根据左右判断 即后序遍历
     */
    /*
    private long[] dfs(TreeNode root) {
        if (root == null) {
            return new long[]{Long.MAX_VALUE, Long.MIN_VALUE};
        }
        long[] left = dfs(root.left);
        long[] right = dfs(root.right);
        long x = root.val;
        if (x > left[1] && x < right[0]) {
            return new long[]{Math.min(left[0], x), Math.max(right[1], x)};
        } else {
            return new long[]{Long.MIN_VALUE, Long.MAX_VALUE};
        }
    }

    public boolean isValidBST(TreeNode root) {
        long[] res = dfs(root);
        return res[1] != Long.MAX_VALUE;
    }*/

    /**
     * 中序遍历
     */
    long preMax = Long.MIN_VALUE;

    public boolean isValidBST(TreeNode root) {
        return dfs(root);
    }

    private boolean dfs(TreeNode root) {
        if (root == null) return true;
        if (!dfs(root.left) || preMax >= root.val) return false;
        preMax = root.val;
        return dfs(root.right);
    }
}
